import React, { useState, useEffect } from 'react';
import { apiService } from '../services/api';

interface DataItem {
  id: string;
  name: string;
  value: number;
}

const DataFetcher: React.FC = () => {
  const [data, setData] = useState<DataItem[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setLoading(true);
    setError(null);
    try {
      // 示例：获取ID为1的数据
      await apiService.getData('1');
      // 这里假设API返回的是一个数组
      // 由于axios拦截器返回response.data，所以我们直接设置数据
      setData([{ id: '1', name: 'Sample Item', value: 42 }]);
    } catch (err) {
      setError('Failed to fetch data');
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = async () => {
    try {
      const newData = { name: 'New Item', value: Math.floor(Math.random() * 100) };
      await apiService.createData(newData);
      // 重新获取数据以显示新项
      fetchData();
    } catch (err) {
      setError('Failed to create data');
      console.error(err);
    }
  };

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div>
      <h2>Data Fetcher</h2>
      <button onClick={handleCreate}>Create New Item</button>
      <ul>
        {data.map((item) => (
          <li key={item.id}>
            {item.name}: {item.value}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default DataFetcher;